import React from "react";

// Context应用场景
// 外层定义一些主题，也无不是很复杂就是数据往下传递的场景

// 创建context
const ThemeContext = React.createContext('ligh')

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      theme: 'light'
    }
  }

  render() {
    return (
      <ThemeContext.Provider value={this.state.theme}>
        <Toolbar />
        <hr />
        <button onClick={this.changeTheme}>change theme</button>
      </ThemeContext.Provider>
    )
  }

  changeTheme = () => {
    this.setState({
      theme: this.state.theme === 'light' ? 'dark' : 'light'
    })
  }
}

// 中间的组件再也不必指明往下传递 theme 了。
function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
      <ThemeLink />
    </div>
  )
}

// 底层组件 class组件
class ThemedButton extends React.Component {
  render() {
    const theme = this.context
    return (
      <div>
        <p>buttons' theme is {theme}</p>
      </div>
    )
  }
}
ThemedButton.contextType = ThemeContext

function ThemeLink(props) {
  return <ThemeContext.Consumer>
    {value => <p>links theme is {value }</p>}
  </ThemeContext.Consumer>
}

export default App